package com.fan.shop.businesslogic;

import org.apache.log4j.Logger;

import com.fan.shop.domain.Stock;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.process.ProcExec;
import com.fan.shop.services.StockService;

public class StockHoldQtyUpdateProcess extends ProcExec<Integer> {

	private static Logger logger = Logger
			.getLogger(StockHoldQtyUpdateProcess.class);
	private StockService stockService;
	private String itemCode;
	private String storeCode;
	private int poQuantity;

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		StockHoldQtyUpdateProcess.logger = logger;
	}

	public StockService getStockService() {
		return stockService;
	}

	public void setStockService(StockService stockService) {
		this.stockService = stockService;
	}

	public String getItemCode() {
		return itemCode;
	}

	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}

	public String getStoreCode() {
		return storeCode;
	}

	public void setStoreCode(String storeCode) {
		this.storeCode = storeCode;
	}

	public int getPoQuantity() {
		return poQuantity;
	}

	public void setPoQuantity(int poQuantity) {
		this.poQuantity = poQuantity;
	}

	@Override
	public Integer processImpl() {

		if (stockService.hasStock(itemCode, storeCode)) {

			Stock stock = stockService.getStock(itemCode, storeCode);
			int holdQty = stock.getHoldQty() + poQuantity;
			int qty = stock.getQuantity() - poQuantity;

			if (qty < 0) {
				setErrorMessage("Not enough quantity left in stock!");
				return ShopGlobalVariables.FAILED;
			}
			if (holdQty < 0) {
				setErrorMessage("Not enough quantity left in holdQty!");
				return ShopGlobalVariables.FAILED;
			} else {

				stock.setHoldQty(holdQty);
				stock.setQuantity(qty);
			}

			try {
				stockService.updateStock(stock);
			} catch (Exception e) {
				setErrorMessage(e.getMessage());
				e.printStackTrace();
				return ShopGlobalVariables.FAILED;
			}

		} else {
			setErrorMessage("Item: " + itemCode + " doesn't exist in store: "
					+ storeCode + "!");
			return ShopGlobalVariables.FAILED;
		}

		return ShopGlobalVariables.SUCCESS;
	}
}
